package com.leo.m1802.d25;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by LEO on 2018/2/25.
 */
public class ThreadTest2 {
    public static final AtomicInteger a = new AtomicInteger(10);
    public static final CyclicBarrier cb = new CyclicBarrier(4, new Runnable() {
        @Override
        public void run() {
            a.decrementAndGet();
            System.out.println("----------------------");
        }
    });

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 4; i++) {
            exec.submit(new WriteTask(i));
        }
        exec.shutdown();
    }

    static class WriteTask implements Runnable{
        final int writeContent;
        WriteTask(int writeContent) {
            this.writeContent = writeContent;
        }
        @Override
        public void run() {
            try {
                while (a.get() > 0) {
                    int file = (a.get() + writeContent) % 4;
                    System.out.println("正在向文件:" + (file + 1) + " 写入：" + (writeContent + 1));
                    Thread.sleep(1000);
                    cb.await();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
